package com.hunttown.mes.service.iot;

import com.hunttown.mes.common.keys.IotKeyConstants;
import com.hunttown.mes.common.cache.Cache;
import com.hunttown.mes.service.*;
import com.hunttown.mes.common.utils.GeneralUtils;
import com.hunttown.mes.common.utils.StringUtils;
import com.hunttown.mes.domain.TransportSmsSendLog;
import com.hunttown.mes.domain.TransportUserCard;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @title: IOT 工具类
 * @author: wangjunfu
 * @date: 2020年10月26日 08:24
 * @description:
 */
@Service
public class IotToolsService {

    private final Cache jedisCache;
    private final TransportUserCardService userCardService;
    private final TransportUserCardLogService userCardLogService;
    private final TransportSmsSendLogService smsSendLogService;
    private final AHelpService aHelpService;
    private final ASendSmsService smsSendService;

    @Autowired
    public IotToolsService(Cache jedisCache, TransportUserCardService userCardService, TransportUserCardLogService userCardLogService, TransportSmsSendLogService smsSendLogService, AHelpService aHelpService, ASendSmsService smsSendService){
        this.jedisCache = jedisCache;
        this.userCardService = userCardService;
        this.userCardLogService = userCardLogService;
        this.smsSendLogService = smsSendLogService;
        this.aHelpService = aHelpService;
        this.smsSendService = smsSendService;
    }

    //region 公司联系电话（从参数配置中取）
    //private static final String telephone = "市场管理部";
    //endregion

    //region 扣除电费

    /**
     * 扣除电费&增加余额
     * 如果扣除失败，则记录到实时帐单的欠费字段中，以便下次扣除
     *
     * @param rechargeType 具体查看RechargeTypeEnum枚举值
     * @param userId       用户ID
     * @param meterNumber  表号
     * @param totalFee     需要扣除的金额
     * @param lastNum      起数
     * @param thisNum      止数
     * @param receiveLogId 接收日志ID
     * @param remark       交易备注
     * @param entId        企业ID
     * @return 扣除成功或失败
     */
    public Boolean deductionBalance(Integer rechargeType, Integer userId, String meterNumber, BigDecimal totalFee, BigDecimal lastNum, BigDecimal thisNum, Integer receiveLogId, String remark, Integer entId) {

        //企业ID为空则获取当前站点的
        if (StringUtils.intIsBlank(entId)) {
            entId = aHelpService.getEnterpriseId();
        }

        //会员卡
        TransportUserCard cardDTO = userCardService.getByUserId(userId, entId);
        if (cardDTO == null) {
            return false;
        }

        TransportUserCard updateDto = new TransportUserCard();
        updateDto.setId(cardDTO.getId());
        updateDto.setEntId(entId);

        //只有1是充值，其它都是扣费
        if (rechargeType == 1) {
            updateDto.setCardValue(cardDTO.getCardValue().add(totalFee));
            updateDto.setAddUpValue(cardDTO.getAddUpValue().subtract(totalFee));
        } else {
            updateDto.setCardValue(cardDTO.getCardValue().subtract(totalFee));
            updateDto.setAddUpValue(cardDTO.getAddUpValue().add(totalFee));
        }

        Boolean isNext = userCardService.updateInfoById(updateDto);

        if (isNext) {
            //当前是电价的那个阶段，缓存key：{企业Id}{年2位}{月2位}{时两位}  value：1峰2谷3平4尖
            String timeStepKey = IotKeyConstants.ELECTRIC_TIME_STEP + entId + GeneralUtils.GenElectricKey();
            String dSign = jedisCache.get(timeStepKey);

            //会员卡日志：插入一条消费记录
            userCardLogService.insertSimple(rechargeType, receiveLogId, userId, meterNumber, cardDTO.getId(), cardDTO.getCardNo(), cardDTO.getCardValue(), totalFee, lastNum, thisNum, (dSign == null ? 0 : Integer.parseInt(dSign)), remark, entId);
        }

        return isNext;
    }
    //endregion

    //region 帐户余额不足通知

    /**
     * 发送短信通知，公用
     *
     * @param templeteId 模板ID
     * @param trueName   姓名
     * @param mobile     手机号
     * @param params     参数
     * @param entId      企业ID
     */
    private void sendNoticeBySms(Integer templeteId, String trueName, String mobile, String[] params, Integer entId) {

        //短信模板：
        //尊敬的{1}您好，您的余额已不足{2}元，为了不影响您用电，请及时充值。如有疑问请联系客服：{3}
        //尊敬的{1}您好，您由于欠费已被分闸，请您先进行充值以便继续使用。如有疑问请联系客服：{2}

        Map<String, String> sendmap = smsSendService.sendSigleSms(mobile, params, templeteId, "", entId);

        //保存发送日志
        TransportSmsSendLog dto = new TransportSmsSendLog();
        dto.setEntId(entId);
        dto.setInfoType(1);
        dto.setUserType(3); //用户：CustomerEnum.USER.getKey()
        dto.setUserId(0);
        dto.setNickName(trueName);
        dto.setMobile(mobile);
        dto.setSmsTopic("");
        dto.setSmsType(6);  //生活缴费：SmsTypeEnum.LIFE.getKey()
        dto.setSmsContent(templeteId + "");
        dto.setCode("");
        dto.setChannelId(1);
        dto.setSendTime(new Date());
        dto.setEffectMinute(0);
        dto.setStatus(Integer.valueOf(sendmap.get("code")));
        dto.setReturnResult(sendmap.get("msg"));
        dto.setSendPeople(1);
        smsSendLogService.insert(dto);

        //发送成功
        if (sendmap.get("code").equals("0")) {
            setSmsNoticeToCache(mobile);
        }
    }
    //endregion

    //region 短信通知缓存（理论上缓存不能配置在service层，这里业务公用，特殊处理）

    // 从缓存中获取通知记录，如果有则不发送。否则增加一条缓存记录，保存一天
    private Boolean isSendSmsNotice(String mobile) {
        String send = jedisCache.get(IotKeyConstants.SMS_NOTICE_BLANCE_MOBILE + mobile);
        return send != null;
    }

    // 往缓存中插入一条通知记录，保存一天
    private void setSmsNoticeToCache(String mobile) {
        jedisCache.set(IotKeyConstants.SMS_NOTICE_BLANCE_MOBILE + mobile, "1", 24 * 60 * 60);
    }

    //endregion

}